﻿using BotDetector.Core.Utilities;
using libsvm;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using TFIDFExample;

namespace BotDetector.Core.SVMModule
{
    public class SvmTest : DetectorBaseModule
    {
        private SvmFileOperator fileOperator = new SvmFileOperator();
        private C_SVC classifier;

        public SvmTest()
        {
            classifier = GetClassifier();

            fileOperator.LoadTFIDF();
        }

        public bool HasClassifier()
        {
            if (classifier != null)
                return true;
            return false;
        }

        public double TestForBot(string text)
        {
            string[] x = {text};
            List<KeyValuePair<int, double>> vectorText = TFIDF.Transform(x, 0).First();

            List<svm_node> svmNodeList = new List<svm_node>();
            foreach (var entity in vectorText)
            {
                svmNodeList.Add(new svm_node() { index = entity.Key, value = entity.Value });
            }

            double rez = classifier.PredictProbabilities(svmNodeList.ToArray())[-1];

            return rez;
        }

        private C_SVC GetClassifier()
        {
            C_SVC classifier;
            svm_problem data_set;

            try{
                data_set = fileOperator.ReadProblemFile();
                classifier = new C_SVC(data_set, KernelHelper.LinearKernel(), 1, probability: true);
            }
            catch
            {
                classifier = null;
            }

            
            return classifier;
        }
    }
}
